home *** CD-ROM | disk | FTP | other *** search
- Path: news1.h1.usa.pipeline.com!usenet
- From: grantp@usa.pipeline.com(Pete)
- Newsgroups: comp.lang.c++
- Subject: Re: Sorting pointers to objects with qsort
- Date: 4 Feb 1996 10:58:59 GMT
- Organization: Kalevi, Inc.
- Message-ID: <4f23hj$m06@news1.usa.pipeline.com>
- NNTP-Posting-Host: 38.8.60.5
- X-PipeUser: grantp
- X-PipeHub: usa.pipeline.com
- X-PipeGCOS: (Pete)
- X-Newsreader: Pipeline USA v3.3.0
-
- On Feb 04, 1996 03:15:12 in article <Sorting pointers to objects with
- qsort>, 'mebust@email.unc.edu (Scott Mebust)' wrote:
-
-
- >I'd appreciate any help on the following problem: sorting pointers to
- >objects (based on object attributes) using qsort.
- >
- >If replying, please send an e-mail as well. Thanks.
- >
- >Scott
- >mebust@email.unc.edu
- >
- >
- >// QUESTION: Why does the following code return the wrong results?
- >
- >// I can't seem to figure this one out. The program below attempts to
- >// sort an array of pointers to String objects using qsort. It compiles
- >// and may *seem* to return the correct results but does not actually
- >// sort the pointers based on any valid data.
- >
- > [... portions deleted ...>
- >
- >class String
- >{
- >public:
- >String(const char* ccp)
- > [.... irrelevant code deleted ....]
- >const char * GetValue(void) const
- >{ return str_; }
- >friend ostream& operator<< (ostream& o, String& s);
- >
- >private:
- >char* str_;
- >};
- ********* here's your problem *******
- >int StrCmpFn (const void* VP1, const void* VP2)
- >{
- >return strcmp(((const String*)VP1)->GetValue(),
- >((const String*)VP2)->GetValue());
- >}
-
- The comparison function actually gets pointers to the
- elements of the array, which themselves are pointers.
- So, you need another dereference:
-
- int StrCmpFn (const void* VP1, const void* VP2)
- {
- const String * s1 = *((String**)(void**)VP1);
- const String * s2 = *((String**)(void**)VP2);
- return strcmp(s1->GetValue(), s2->GetValue());
- }
-
- Warning! I didn't actually test this code so I may have a
- subtle error -- it's the idea that counts:-) VP1 and VP2
- are actually void** so you must first cast them to such.
- Then you cast the void** to String** and dereference
- the result to come up with String*.
-
- You can combine all this into a single line, if you like,
- but as an illustration it would look messy and hard to
- decipher.
-
- BTW, the 'casting' is all done by the compiler. It does
- not generate any executable code so the cost is totally
- in the amount of typing you have to do (and a millisec
- or two by the compiler trying to figure out what you're
- after).
-
-
- --
- Pete Grant
- Kalevi, Inc.
- Object Oriented Software Development
-